package com.ebupt.migu.music.propagate.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ebupt.migu.music.commons.constants.ResultMsg;
import com.ebupt.migu.music.commons.constants.StrategyConstants;
import com.ebupt.migu.music.commons.sms.Sender;
import com.ebupt.migu.music.propagate.dto.SendDto;
import com.ebupt.migu.music.propagate.service.PropagateSendService;
import com.ebupt.migu.propagate.PropagateInfo;
import com.ebupt.migu.propagate.PropagateRedisBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 服务云全局弹窗接口
 * @author tz
 */
@Service
@Slf4j
public class PropagateSendServiceImpl implements PropagateSendService {

    @Value("${path.propagate_upload}")
    private String uploadPath;
    @Value("${ack.str}")
    private String str;
    @Value("${ack.start}")
    private Integer start;
    @Value("${ack.end}")
    private Integer end;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private Sender sender;

    @Override
    public ResultMsg send(SendDto dto) {
        //下发还是存文件
        AtomicBoolean isSend = new AtomicBoolean(false);
        //获取缓存的宣发策略列表
        Set<Object> members = redisTemplate.opsForSet().members(StrategyConstants.STRATEGY_LIST);
        if (members != null && members.size() > 0) {
            members.forEach(m -> {
                Object o = redisTemplate.opsForValue().get(m);
                assert o != null;
                PropagateRedisBean bean = JSON.parseObject(o.toString(), PropagateRedisBean.class);
                //判断彩铃id是否属于当前策略
                PropagateInfo info = isHasRingId(bean.getInfos(), dto.getRbtId());
                if (Optional.ofNullable(info).isPresent()) {
                    //判断是否属于可运营时间段
                    if (isCanSend()) {
                        //获取短信内容
                        String content = info.getSmsContent();
                        //判断激活码类型
                        if (bean.getActivationCodeType() == 1) {
                            Object ack = redisTemplate.opsForList().rightPop(bean.getActivationCodeKey());
                            if (ObjectUtil.isNotEmpty(ack)) {
                                //激活码拼接短信
                                content = content.replaceAll(str, ack.toString());
                                isSend.set(true);
                            }
                        }
                        if (bean.getActivationCodeType() == 2) {
                            //todo 通过接口获取激活码
                        }
                        if (bean.getActivationCodeType() == 3) {
                            isSend.set(true);
                        }
                        if (isSend.get() && bean.getSendWay() == 1) {
                            sender.sendPropagateSms(info.getStrategyId(),dto.getMsisdn(),content,bean.getConf());
                        }
                    } else {
                        //不在运营时间段，记录调用到redis缓存里面
                        redisTemplate.opsForList().leftPush(StrategyConstants.PROPAGATE_CACHE,JSON.toJSONString(dto));
                        isSend.set(true);
                    }
                }
            });
            //未在进行中策略找到对应彩铃id，可能已完成任务，文件记录每次调用信息
            if (!isSend.get()) {
                saveFile(dto);
            }
        }
        return new ResultMsg();
    }

    /**
     *  返回存在彩铃id的短信信息
     * @param infos
     * @param rbtId
     * @return
     */
    private PropagateInfo isHasRingId(List<PropagateInfo> infos, String rbtId){
        List<String> list;
        for (PropagateInfo info : infos) {
             list = Arrays.asList(info.getRingIds().split(","));
            if (list.contains(rbtId)) {
                return info;
            }
        }
        return null;
    }

    /**
     *  判断当前时间是否在当天的9点到22点之间
     * @return
     */
    private boolean isCanSend(){
        int hour = LocalDateTime.now().getHour();
        return hour >= start && hour < end;
    }

    /**
     * 多余信息存文件
     * @param dto
     */
    private void saveFile(SendDto dto){
        FileWriter fw = new FileWriter(uploadPath + StrategyConstants.PROPAGATE_SAVE);
        String str = dto.getMsisdn() + "," +
                dto.getRbtId() + "," +
                DateUtil.now() + System.getProperty("line.separator");
        fw.write(str,true);
    }
}
